#ifndef BEHAVIOR_TREE_HPP
#define BEHAVIOR_TREE_HPP

#include <cstdlib>
#include <ctime>
#include <functional>
#include <vector>

#include "fsm.hpp"

class BehaviorTree {
 public:
  using Action = std::function<void()>;

  explicit BehaviorTree(DoorFSM& fsm) : fsm(fsm), currentStep(0) {
    actions.push_back([this, &fsm]() {
      std::cout << "Step 0: Attempting to unlock the door..." << std::endl;
      if (fsm.getState() == DoorFSM::LOCKED) {
        fsm.unlock();
      }
    });
    actions.push_back([this, &fsm]() {
      std::cout << "Step 1: Attempting to open the door..." << std::endl;
      if (fsm.getState() == DoorFSM::UNLOCKED || fsm.getState() == DoorFSM::CLOSED) {
        fsm.open();
      }
    });
    actions.push_back([this, &fsm]() {
      std::cout << "Step 2: Attempting to half open the door..." << std::endl;
      if (fsm.getState() == DoorFSM::OPENED) {
        fsm.halfOpen();
      }
    });
    actions.push_back([this, &fsm]() {
      std::cout << "Step 3: Attempting to jam the door..." << std::endl;
      if (fsm.getState() == DoorFSM::HALF_OPEN) {
        fsm.jam();
      }
    });
    actions.push_back([this, &fsm]() {
      std::cout << "Step 4: Attempting to unjam the door..." << std::endl;
      if (fsm.getState() == DoorFSM::JAMMED) {
        fsm.unjam();
      }
    });
    actions.push_back([this, &fsm]() {
      std::cout << "Step 5: Attempting to lock the door..." << std::endl;
      if (fsm.getState() == DoorFSM::CLOSED) {
        fsm.lock();
      }
    });

    std::srand(std::time(nullptr));  // 初始化随机数生成器
  }

  void run() {
    while (currentStep < actions.size()) {
      if (std::rand() % 2 == 0) {  // 50%的概率执行当前步骤
        actions[currentStep]();
      } else {
        std::cout << "Skipping step " << currentStep << " due to random choice." << std::endl;
      }
      currentStep++;
    }
    currentStep = 0;
  }

 private:
  DoorFSM& fsm;
  std::vector<Action> actions;
  int currentStep;
};

#endif  // BEHAVIOR_TREE_HPP
